<template>
  <basic-container>
    <el-calendar v-model="calendarData" v-loading="loading">
      <template
        slot="dateCell"
        slot-scope="{date, data}">
        <div class="date-cell" :class="data.isSelected ? 'is-selected' : ''">
          <div class="calendar-day">
            {{ data.day.split('-').slice(1).join('-') }}
          </div>
          <el-row :span="24">
            <el-col :span=24>
              <div class="dinner date-item" @click="handleEditItem(data.day)">
                <el-popover
                  v-if="formatCookbookListRemark(data)"
                  placement="top-start"
                  title="备注"
                  width="200"
                  trigger="hover"
                  :content="formatCookbookListRemark(data)">
                  <div slot="reference">
                    <div
                      v-if="formatSchedule(data).length > 0"
                    >
                      <span>{{ `个性餐 * ${formatSchedule(data).length}` }}</span>
                      <span style="color: red" :key="cookbookIndex"
                            v-if="cookbookItem.mainCourseType && cookbookItem.mainCourseType !== ''"
                            v-for="(cookbookItem, cookbookIndex) in formatSchedule(data)">
                    <span v-if="cookbookIndex === 0">(</span>
                    <span v-else>+</span>
                    {{ cookbookItem.mainCourseType }}
                    <span v-if="cookbookIndex === formatSchedule(data).length - 1">)</span>
                  </span>
                    </div>
                    <div
                      v-if="preCookbookCount(data, 1, 2).length > 0"
                    ><span>{{ `中式A餐 * ${preCookbookCount(data, 1, 2).length}` }}</span></div>
                    <div
                      v-if="preCookbookCount(data, 2, 2).length > 0"
                    ><span>{{ `中式B餐 * ${preCookbookCount(data, 2, 2).length}` }}</span></div>
                    <div
                      v-if="preCookbookCount(data, 1 ,1).length > 0"
                    ><span>{{ `西式C餐 * ${preCookbookCount(data, 1, 1).length}` }}</span></div>
                    <div
                      v-if="preCookbookCount(data, 2, 1).length > 0"
                    ><span>{{ `西式D餐 * ${preCookbookCount(data, 2, 1).length}` }}</span></div>
                    <div>
                      <span style="color: red">* 备注</span>
                    </div>
                  </div>
                </el-popover>
                <div v-else>
                  <div
                    v-if="formatSchedule(data).length > 0"
                  >
                    <span>{{ `个性餐 * ${formatSchedule(data).length}` }}</span>
                    <span style="color: red" :key="cookbookIndex"
                          v-if="cookbookItem.mainCourseType && cookbookItem.mainCourseType !== ''"
                          v-for="(cookbookItem, cookbookIndex) in formatSchedule(data)">
                    <span v-if="cookbookIndex === 0">(</span>
                    <span v-else>+</span>
                    {{ cookbookItem.mainCourseType }}
                    <span v-if="cookbookIndex === formatSchedule(data).length - 1">)</span>
                  </span>
                  </div>
                  <div
                    v-if="preCookbookCount(data, 1, 2).length > 0"
                  ><span>{{ `中式A餐 * ${preCookbookCount(data, 1, 2).length}` }}</span></div>
                  <div
                    v-if="preCookbookCount(data, 2, 2).length > 0"
                  ><span>{{ `中式B餐 * ${preCookbookCount(data, 2, 2).length}` }}</span></div>
                  <div
                    v-if="preCookbookCount(data, 1 ,1).length > 0"
                  ><span>{{ `西式C餐 * ${preCookbookCount(data, 1, 1).length}` }}</span></div>
                  <div
                    v-if="preCookbookCount(data, 2, 1).length > 0"
                  ><span>{{ `西式D餐 * ${preCookbookCount(data, 2, 1).length}` }}</span></div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-calendar>
    <el-drawer
      title="可选菜品"
      :visible.sync="addFoodVisible"
      append-to-body
      :before-close="handleAddFoodClose"
      size="600px"
    >
      <basic-container>
        <el-form :model="cookbookForm" ref="form" label-width="80px" class="food-select-form">
          <el-form-item label="一键添加份数: " label-width="120px">
          <el-input-number :min="1" controls-position="right" style="margin-right: 10px" v-model="foodSelectCount"></el-input-number>
          </el-form-item>
          <el-form-item label="A餐中式餐菜品: " label-width="120px">
            <el-tag v-if="dayLunchNutrimealFoodList.length !== 0" :key="index"
                    v-for="(item, index) in dayLunchNutrimealFoodList"
                    style="margin-right: 10px"
                    :type="item.status === 1 ? 'primary' : 'danger'"
                    @click="selectFood(item)"
            >
              {{ item.foodName }}
            </el-tag>
            <el-button type="primary" size="small"
                       @click="addMultiFoods(dayLunchNutrimealFoodList, 1)">
              一键添加
            </el-button>
            <el-tag type="danger" v-if="dayLunchNutrimealFoodList.length === 0">未配置</el-tag>
          </el-form-item>
          <el-form-item label="A餐西式餐菜品: " label-width="120px">
            <el-tag v-if="dayLunchReducedFoodList.length !== 0" :key="index"
                    v-for="(item, index) in dayLunchReducedFoodList"
                    style="margin-right: 10px"
                    :type="item.status === 1 ? 'primary' : 'danger'"
                    @click="selectFood(item)"
            >
              {{ item.foodName }}
            </el-tag>
            <el-button v-if="dayLunchReducedFoodList.length !== 0" type="primary" size="small"
                       @click="addMultiFoods(dayLunchReducedFoodList, 1)">
              一键添加
            </el-button>
            <el-tag type="danger" v-if="dayLunchReducedFoodList.length === 0">未配置</el-tag>
          </el-form-item>
          <el-form-item label="B餐中式餐菜品: " label-width="120px">
            <el-tag v-if="dayDinnerNutrimealFoodList.length !== 0" :key="index"
                    v-for="(item, index) in dayDinnerNutrimealFoodList"
                    style="margin-right: 10px"
                    :type="item.status === 1 ? 'primary' : 'danger'"
                    @click="selectFood(item)"
            >
              {{ item.foodName }}
            </el-tag>
            <el-button v-if="dayDinnerNutrimealFoodList.length !== 0" type="primary" size="small"
                       @click="addMultiFoods(dayDinnerNutrimealFoodList, 2)">
              一键添加
            </el-button>
            <el-tag type="danger" v-if="dayDinnerNutrimealFoodList.length === 0">未配置</el-tag>
          </el-form-item>
          <el-form-item label="B餐西式餐菜品: " label-width="120px">
            <el-tag v-if="dayDinnerReducedFoodList.length !== 0" :key="index"
                    v-for="(item, index) in dayDinnerReducedFoodList"
                    style="margin-right: 10px"
                    :type="item.status === 1 ? 'primary' : 'danger'"
                    @click="selectFood(item)"
            >
              {{ item.foodName }}
            </el-tag>
            <el-button v-if="dayDinnerReducedFoodList.length !== 0" type="primary" size="small"
                       @click="addMultiFoods(dayDinnerReducedFoodList, 2)">
              一键添加
            </el-button>
            <el-tag type="danger" v-if="dayDinnerReducedFoodList.length === 0">未配置</el-tag>
          </el-form-item>
          <el-form-item label="中式餐备菜: " label-width="120px">
            <el-tag v-if="dayOtherNutrimealFoodList.length !== 0" :key="index"
                    v-for="(item, index) in dayOtherNutrimealFoodList"
                    style="margin-right: 10px"
                    :type="item.status === 1 ? 'primary' : 'danger'"
                    @click="selectFood(item)"
            >
              {{ item.foodName }}
            </el-tag>
            <el-tag type="danger" v-if="dayOtherNutrimealFoodList.length === 0">未配置</el-tag>
          </el-form-item>
          <el-form-item label="西式餐备菜: " label-width="120px">
            <el-tag v-if="dayOtherReducedFoodList.length !== 0" :key="index"
                    v-for="(item, index) in dayOtherReducedFoodList"
                    style="margin-right: 10px"
                    :type="item.status === 1 ? 'primary' : 'danger'"
                    @click="selectFood(item)"
            >
              {{ item.foodName }}
            </el-tag>
            <el-tag type="danger" v-if="dayOtherReducedFoodList.length === 0">未配置</el-tag>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddFoodClose">取 消</el-button>
      </span>
      </basic-container>
    </el-drawer>
    <el-dialog title="选餐"
               append-to-body
               :visible.sync="itemVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               width="70%">
      <el-form :model="cookbookForm" ref="form" label-width="80px" class="food-select-form">
        <el-form-item label="日期: " label-width="120px">
          <el-tag>{{ cookbookForm.date }}</el-tag>
        </el-form-item>
        <el-form-item label="类型: " label-width="120px">
          <el-tag v-if="cookbookForm.meal === 1" type="warning">A 餐</el-tag>
          <el-tag v-else-if="cookbookForm.meal === 2" type="success">B 餐</el-tag>
          <el-tag v-else type="success">未 知</el-tag>
        </el-form-item>
        <el-form-item label="修改地址: " label-width="120px">
          <el-select style="width: 300px;" placeholder="请选择地址" v-model="addressIndex" @change="addressChange" clearable>
            <el-option :key="index" v-for="(address, index) in addressList" :value="index" :label="address.isTakeSelf && address.isTakeSelf === 1 ? `【${address.merchantName}】自取` : `【${address.merchantName}】 ${address.addressText}`">
              <span v-if="address.isTakeSelf && address.isTakeSelf === 1">【{{ address.merchantName }}】自取</span>
              <span v-else>【{{ address.merchantName }}】{{ address.addressText }}(距离: {{ address.distance }}千米) {{ address.public ? '【拼团地址】' : '' }}</span>
            </el-option>
          </el-select>

          <el-button type="primary" style="margin-left: 20px" @click="updateReceiver(cookbookForm.date, cookbookForm.meal)">更新收货地址</el-button>
        </el-form-item>
        <el-form-item label="主食类型: " label-width="120px">
          <div>
            <el-select v-model="cookbookForm.mainCourseType">
              <el-option value="全白米" label="全白米">全白米</el-option>
              <el-option value="米类全粗粮" label="米类全粗粮">米类全粗粮</el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="联系人: " label-width="120px">
          <el-input style="width: 70%" v-model="cookbookForm.receiver"></el-input>
        </el-form-item>
        <el-form-item label="联系电话: " label-width="120px">
          <el-input style="width: 70%" v-model="cookbookForm.telephone"></el-input>
        </el-form-item>
        <el-form-item label="备注: " label-width="120px">
          <div>
            <el-input style="width: 70%" type="textarea" v-model="cookbookForm.remark"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="" label-width="120px">
          <el-button type="primary" @click="addCookbook(cookbookForm.meal)">加餐</el-button>
        </el-form-item>
        <el-form-item :label="`${memberCookbook.isGeneral === 1 ? '标准餐' : '个性餐'}: `" label-width="120px" :key="index" v-for="(memberCookbook, index) in memberCookbookList">
          <el-tag v-if="memberCookbook.foodList.length !== 0" :key="foodIndex"
                  v-for="(item, foodIndex) in memberCookbook.foodList"
                  style="margin-right: 10px"
                  closable
                  :type="item.status === 1 ? 'primary' : 'danger'"
                  @close="handleRemoveFood(index, foodIndex)"
          >
            {{ item.foodName }}
          </el-tag>
          <el-tag type="warning" style="margin-right: 10px" v-if="memberCookbook.remark && memberCookbook.remark !== ''">备注: {{ memberCookbook.remark }}</el-tag>
          <el-tag type="warning" style="margin-right: 10px" v-if="memberCookbook.remark1 && memberCookbook.remark1 !== ''">其他备注: {{ memberCookbook.remark1 }}</el-tag>
          <el-button type="text" icon="el-icon-plus"  @click="addFood(index)">添加菜品</el-button>
          <el-button type="primary" @click="updateMemberCookbook(memberCookbook)">{{ memberCookbook.id && memberCookbook.id !== '' ? '更新选餐' : '保存选餐' }}</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="stopCookbook(memberCookbook)">取消</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCookbookClose">取 消</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { dateFormat } from "../../../util/date";
import { getListAll as memberCookbookList, submit, addBatch, stop, goOn, preGeneralMemberCookbook, updateReceiver } from "@/api/member/member_cookbook"
import { memberWeekAddress } from "@/api/address/open_address"
import { getList as cookbookList } from "@/api/cookbook/cookbook";

export default {
  name: "MemberCookbook",
  props: {
    form: {
      type: Object,
      default: () => {}
    },
    addressList: {
      type: Array,
      default: () => {}
    }
  },
  data() {
    return {
      calendarData: '',
      loading: false,
      data: [],
      monthCookbookList: [],
      itemVisible: false,
      cookbookForm: {
        remark: ''
      },
      foodSelectedList: {},
      foodSelectCount: 1,
      dayLunchNutrimealFoodList: [],
      dayDinnerNutrimealFoodList: [],
      dayLunchReducedFoodList: [],
      dayDinnerReducedFoodList: [],
      dayOtherNutrimealFoodList: [],
      dayOtherReducedFoodList: [],
      weekPackagesCycle: {},
      addFoodIndex: '',
      addFoodVisible: false,
      memberCookbookList: [],
      addressIndex: '',
      addressForm: {},
    }
  },
  computed: {
    searchDateRange() {
      const date = this.calendarData !== '' ? this.calendarData : new Date()
      const monthStart = new Date(date.getFullYear(), date.getMonth(), 1)
      const monthEnd = new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59)
      return [dateFormat(monthStart), dateFormat(monthEnd)]
    },
    formatSchedule() {
      return (data) => {
        const list = []
        this.data.map(ele => {
          if (data.day === ele.date && (ele.isGeneral != 1 || (ele.remark && ele.remark !== '') || (ele.remark1 && ele.remark1 !== ''))) {
            list.push(ele)
          }
        })
        return list
      }
    },
    formatCookbookList() {
      return (data) => {
        const list = []
        this.data.map(ele => {
          if (data.day === ele.date) {
            list.push(ele)
          }
        })
        return list
      }
    },
    formatCookbookListRemark() {
      return (data) => {
        const cookbookList = this.formatCookbookList(data)
        const remarkList = []

        cookbookList.forEach(item => {
          if (!remarkList.includes(item.remark)) {
            remarkList.push(item.remark)
          }
          if (!remarkList.includes(item.remark1)) {
            remarkList.push(item.remark1)
          }
        })

        return remarkList.join(' ')
      }
    },
    packagesCycle() {
      try {
        return JSON.parse(this.form.packagesCycle)
      } catch (e) {
        return {}
      }
    },
    preCookbookCount() {
      return (data, meal, type) => {
        const list = []
        this.data.map(ele => {
          if (data.day === ele.date && meal == ele.meal && ele.isGeneral == 1 && (!ele.remark || ele.remark === '') && (!ele.remark1 || ele.remark1 === '') && ele.type == type) {
            list.push(ele)
          }
        })
        return list
      }
    }
  },
  watch: {
    calendarData() {
      this.init()
    },
  },
  mounted() {
    preGeneralMemberCookbook(this.form.id).then(() => {
      this.init()
    })
  },
  methods: {
    updateReceiver(date, meal) {
      this.addressForm.date = date
      this.addressForm.meal = meal
      this.$confirm("确定修改收件地址?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateReceiver(this.form.id, date, meal, this.cookbookForm.telephone, this.cookbookForm.receiver, this.cookbookForm.address, this.cookbookForm.merchantId, this.cookbookForm.addressId).then(res => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$emit('reload')
          this.handleCookbookClose()
          this.addressIndex = ''
        })
      })
    },
    addressChange(index) {
      this.$set(this.cookbookForm, 'address', this.addressList[index].addressText)
      this.$set(this.cookbookForm, 'merchantId', this.addressList[index].merchantId)
      this.$set(this.cookbookForm, 'addressId', this.addressList[index].id)
      if (this.addressList[index].isPublic !== 1) {
        this.$set(this.cookbookForm, 'receiver', this.addressList[index].name)
        this.$set(this.cookbookForm, 'telephone', this.addressList[index].tel)
      }
    },
    addCookbook(meal) {
      this.memberCookbookList.push({
        memberId: this.form.id,
        foodList: [],
        isGeneral: 2,
        meal: meal,
        type: 1,
        isAdd: 1,// 是加餐
      })
    },
    formatRow(row) {
      row.telephone = this.cookbookForm.telephone
      row.receiver = this.cookbookForm.receiver
      row.address = this.cookbookForm.address
      row.merchantId = this.cookbookForm.merchantId
      row.addressId = this.cookbookForm.addressId
      row.meal = this.cookbookForm.meal
      row.date = this.cookbookForm.date
      row.remark = this.cookbookForm.remark
      row.mainCourseType = this.cookbookForm.mainCourseType
      row.foods = JSON.stringify(row.foodList)
    },
    stopCookbook(row) {
      this.formatRow(row)
      stop(row).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "取消成功!"
          });
          this.handleCookbookClose()
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      })
    },
    addFood(index) {
      this.addFoodVisible = true
      this.addFoodIndex = index
    },
    handleAddFoodClose() {
      this.addFoodIndex = ''
      this.addFoodVisible = false
    },
    handleRemoveFood(memberCookbookIndex, foodIndex) {
      this.memberCookbookList[memberCookbookIndex].foodList.splice(foodIndex, 1)
      this.$forceUpdate()
    },
    selectFood(item) {
      if (this.memberCookbookList[this.addFoodIndex].foodList && Array.isArray(this.memberCookbookList[this.addFoodIndex].foodList)) {
        this.memberCookbookList[this.addFoodIndex].foodList.push(item.foodVO)
      } else {
        this.memberCookbookList[this.addFoodIndex].foodList = []
        this.memberCookbookList[this.addFoodIndex].foodList.push(item.foodVO)
      }
      this.$forceUpdate()
    },
    addMultiFoods(foodList, meal) {
      if (!this.cookbookForm.telephone || this.cookbookForm.telephone === '') {
        this.$message.warning('请先配置联系电话！')
        return
      }
      if (!this.cookbookForm.addressId || this.cookbookForm.addressId === '') {
        this.$message.warning('请先配置配送地址！')
        return
      }

      const foods = []
      foodList.forEach(item => {
        foods.push(item.foodVO)
      })

      console.log(foodList)

      const row = {
        foodList: foods,
        memberId: this.form.id,
      }

      this.formatRow(row)
      row.meal = meal
      row.isGeneral = 2
      addBatch(row, this.foodSelectCount).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.handleAddFoodClose()
          this.handleCookbookClose()
        }
      })
    },
    selectFoods(foodList) {
      this.memberCookbookList[this.addFoodIndex].foodList = []
      foodList.forEach(item => {
        this.memberCookbookList[this.addFoodIndex].foodList.push(item.foodVO)
      })
      this.$forceUpdate()
    },
    init() {
      const params = {
        startDate: this.searchDateRange[0],
        endDate: this.searchDateRange[1],
        memberId: this.form.id
      }
      this.loading = true
      memberCookbookList(params).then(res => {
        this.data = res.data.data
        this.loading = false
      })
    },
    handleEditItem(date) {
      this.itemVisible = true
      this.cookbookForm.date = date
      this.getDayFoodList(date)
      this.getDayCookbook(date)
      this.getWeekPackageCycle(date)
    },
    getDayFoodList(date) {
      // init
      this.memberCookbookList = []
      this.data.forEach(item => {
        if (item.date === date) {
          const addItem = item
          addItem.foodList = JSON.parse(item.foods)
          this.memberCookbookList.push(addItem)
        }
      })
    },
    getWeekPackageCycle(date) {
      memberWeekAddress(this.form.id, date).then((res) => {
        const data = res.data.data
        this.$set(this.cookbookForm, 'telephone', data.tel)
        this.$set(this.cookbookForm, 'receiver', data.memberName)
        this.$set(this.cookbookForm, 'address', data.addressText)
        this.$set(this.cookbookForm, 'merchantId', data.merchantId)
        this.addressList.forEach((item, index) => {
          if (item.id.toString() === data.id.toString()) {
            this.addressIndex = index
            this.cookbookForm.addressId = data.id
          }
        })
      })
    },
    getDayCookbook(date) {
      const params = {
        startDate: date,
        endDate: date
      }
      cookbookList(params).then(res => {
        const data = res.data.data
        data.forEach(item => {
          if (item.type === 1 && item.meal === 1) {
            this.dayLunchReducedFoodList = item.cookbookFoodList
          } else if (item.type === 2 && item.meal === 1) {
            this.dayLunchNutrimealFoodList = item.cookbookFoodList
          } else if (item.type === 1 && item.meal === 2) {
            this.dayDinnerReducedFoodList = item.cookbookFoodList
          } else if (item.type === 2 && item.meal === 2) {
            this.dayDinnerNutrimealFoodList = item.cookbookFoodList
          } else if (item.meal === 3 && item.type === 1) {
            this.dayOtherReducedFoodList = item.cookbookFoodList
          } else if (item.meal === 3 && item.type === 2) {
            this.dayOtherNutrimealFoodList = item.cookbookFoodList
          }
        })
        // this.addDefaultCookbookList(date, meal)
      })
    },
    handleCookbookClose() {
      this.itemVisible = false
      this.cookbookForm = {}
      this.foodSelectedList = {}
      this.dayDinnerNutrimealFoodList = []
      this.dayLunchNutrimealFoodList = []
      this.dayDinnerReducedFoodList = []
      this.dayLunchReducedFoodList = []
      this.dayOtherNutrimealFoodList = []
      this.dayOtherReducedFoodList = []
      this.memberCookbookList = []
      this.addressForm = {}
      // this.foodSelectCount = 1
      this.init()
    },
    updateMemberCookbook(row) {
      if (!this.cookbookForm.telephone || this.cookbookForm.telephone === '') {
        this.$message.warning('请先配置联系电话！')
        return
      }
      if (!this.cookbookForm.addressId || this.cookbookForm.addressId === '') {
        this.$message.warning('请先配置配送地址！')
        return
      }

      this.formatRow(row)
      row.isGeneral = 2
      submit(row).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.handleCookbookClose()
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.date-item {
  height: 180px;
  opacity: 0.8;
}

.lunch {
  background-color: #f0f175;
}

.dinner {
  background-color: #7ff176;
}

.panty {
  width: 100%;
}

.date-item-meal {
  margin: 5px;
}

</style>
<style lang="scss" scoped>
.el-calendar-table:not(.is-range) td.next, .el-calendar-table:not(.is-range) td.prev {
  pointer-events: none !important;
  cursor: default !important;
  color: white;
  background-color: white;
  .date-item {
    background-color: white;
  }
}

.el-select-dropdown .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0 20px !important;
}
</style>
